package cn.group7.padserver.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author 谷汉斌
 * @description 初始处理请求和响应过滤器（配置request和response）
 * @createTime 2024/7/31 下午3:21
 */
@Slf4j
public class WebBaseFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException, IOException {
        log.info("开始执行WebBaseFilter*************");
        HttpServletResponse res = (HttpServletResponse) response;
        //解决跨域问题
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        res.setHeader("Access-Control-Max-Age", "3600");
        res.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Accept, x-requested-with, Cache-Control");
        // 设置响应头
        res.setHeader("Content-Type", "application/json;charset=UTF-8");
        //浏览器会有个欲请求（"OPTIONS"），请求通过才会发送get/post请求，所以直接放行
        HttpServletRequest req = (HttpServletRequest) request;
        if ("OPTIONS".equals(req.getMethod())) {
            res.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        chain.doFilter(request, res);
    }

    @Override
    public void destroy() {

    }
}
